<template>
  <div class="salary-comparison">
    <!-- 公司标签栏 -->
    <div class="company-header">
     <div
        v-for="(company, index) in visibleCompanies"
        :key="index"
        class="company-tab"
        :class="{ active: selectedCompanyIndices && selectedCompanyIndices.includes(getCompanyOriginalIndex(company)) }"
        @click="toggleCompany(getCompanyOriginalIndex(company))"
      >
        <span v-if="company.logo_url" class="company-logo-image">
          <img :src="getFullLogoUrl(company.logo_url)" :alt="company.name" class="company-logo-img" />
        </span>
        <span v-else class="company-logo">{{ company.logo }}</span>
        <span class="company-name">{{ company.name }}</span>
        <span class="company-count">{{ company.count }}</span>
      </div>
      <!-- 搜索输入框和按钮 -->
      <div class="search-container">
      <el-select
        v-model="searchQuery"
        placeholder="搜索更多公司..."
        style="width: 200px; margin-right: 10px;"
        filterable
        @change="handleSearchChange"
      >
        <el-option
          v-for="company in companies"
          :key="company.id"
          :label="company.name"
          :value="company.id"
        />
      </el-select>
              
        <el-button type="primary" @click="addSalary">添加薪酬</el-button>
      </div>
    </div>

    <!-- 薪资对比图表 -->
    <el-row justify="center" :gutter="1">
      <el-col
        v-for="(col, colIndex) in processedColumns"
        :key="colIndex"
        :span="Math.max(3, Math.floor(24 / processedColumns.length))"
      >

         <!-- 公司标题 -->
          <div class="company-header-title">
              <el-icon class="arrow left-arrow" @click="moveColumnLeft(colIndex)"><arrow-left /></el-icon>
                    <div class="company-header-in-chart">
                      <span v-if="getCompanyLogoUrl(selectedCompanyIndices[colIndex])" class="company-logo-image">
                        <img :src="getFullLogoUrl(getCompanyLogoUrl(selectedCompanyIndices[colIndex]))" :alt="getCompanyName(selectedCompanyIndices[colIndex])" class="company-logo-img" />
                      </span>
                      <span v-else class="company-logo">{{ getCompanyLogo(selectedCompanyIndices[colIndex]) }}</span>
                      <span class="company-name">{{ getCompanyName(selectedCompanyIndices[colIndex]) }}</span>
                    </div>
                     <el-icon class="arrow right-arrow" @click="moveColumnRight(colIndex)"><arrow-right /></el-icon>
          </div>
          
        
        <div
          class="career-chart"
          :style="{ background: `linear-gradient(to bottom, ${getColumnGradient(colIndex)})` }"
          @click="openSalaryDialog(colIndex)"
        >
          <div
            v-for="(item, index) in col"
            :key="index"
            class="row"
            :style="{ height: `${item.height}px`, fontSize: `${item.fontSize}px` }"
          >
            <div class="content-wrapper">
              <div class="level">{{ item.level }}</div>
              <div class="title">{{ item.title }}</div>
              <div class="salary">{{ item.salary }}</div>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 弹窗 -->
    <el-dialog v-model="dialogVisible" title="薪酬详情" width="600px">
      <XinZhiFenXi :salaryData="currentSalaryData" />
      <template #footer>
        <el-button @click="dialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>



<script>
import { ref, watch, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router'
import XinZhiFenXi from './XinZhiFenXi.vue';
import { ArrowLeft, ArrowRight } from '@element-plus/icons-vue';
import { CampatydataApi,SalariesdataApi } from '@/utils/api';
import apiConfig from '../utils/apiConfig';

export default {
  components: {
    XinZhiFenXi,
    ArrowLeft,
    ArrowRight
  },

  setup() {
    const dialogVisible = ref(false);
    const currentSalaryData = ref(null);
    const companySalaryData = ref([]); // 使用真实数据
    const selectedCompanyIndices = ref([0, 1, 2]); // 默认选前3家
    const companies = ref([]); // 存储从API获取的公司列表
     const router = useRouter(); // 获取路由实例
    
    // 修改 visibleCompanies 的计算逻辑
    const visibleCompanies = computed(() => {
      // 检查是否选择了前5家公司以外的公司
      const hasSelectedOutsideTop5 = selectedCompanyIndices.value.some(index => index >= 5);
      
      // 如果选择了前5家以外的公司，则显示所有选中的公司
      if (hasSelectedOutsideTop5) {
        // 显示选中的公司（最多5个）
        return selectedCompanyIndices.value.map(index => companies.value[index]);
      } else {
        // 否则显示前5家公司
        return companies.value.slice(0, 5);
      }
    });
    
    // 新增：搜索查询变量
    const searchQuery = ref('');
    
  // ... existing code ...
    // 获取公司数据
    const fetchCompanies = async () => {
      try {
        const response = await CampatydataApi.getCampatyDataList();
        companies.value = response.data.map((company, index) => ({
          id: company.id,
          name: company.name,
          logo: company.name.charAt(0).toUpperCase(), // 使用公司名称首字母作为logo
          count: company.salary_report_count ? company.salary_report_count : 0, // 使用部门数量作为count
          logo_url: company.logo_url || null, // 添加logo_url字段
          ...company
        }));
        
        // 初始化选中项
        selectedCompanyIndices.value = [0, 1, 2].filter(i => i < companies.value.length);
      } catch (error) {
        console.error('获取公司数据失败:', error);
      }
    };
    
 // ... existing code ...
    // 获取薪资数据
    const fetchSalaryData = async () => {
      console.log('开始获取薪资数据...');
      try {
        // 创建包含选中公司ID的参数列表
        const companyIds = selectedCompanyIndices.value.map(index => companies.value[index].id);
        console.log('选中的公司IDs:', companyIds);
        
        // 为每个选中的公司获取薪资数据
        const salaryPromises = companyIds.map(companyId => {
          return SalariesdataApi.getSalaryTotalByCompanyId({
            company_id: companyId,
            title: '技术研发'
          });
        });
        
        // 等待所有请求完成
        const salaryResponses = await Promise.all(salaryPromises);
        console.log('薪资数据响应:', salaryResponses);
        
        // 处理返回的数据
        const salaryData = salaryResponses.map((response, index) => {
          const companyId = companyIds[index];
          const company = companies.value.find(c => c.id === companyId);
          
          if (!response || !response['技术研发'] || !response['技术研发'][company.name]) {
            console.warn(`未找到公司 ${company.name} 的薪资数据`);
            return { levels: [] };
          }
          
          const companyData = response['技术研发'][company.name];
          const levels = companyData.levels.map(level => {
            return {
              level_code: level.level_code || '',
              level_name: level.level_name || '',
              min_salary: level.total_comp_twenty_five_quantile || 0,
              max_salary: level.total_comp_seventy_five_quantile || 0,
              height: calculateHeight(level.total_comp_twenty_five_quantile, level.total_comp_seventy_five_quantile)
            };
          });
          
          return { levels };
        });
        
        companySalaryData.value = salaryData;
        console.log('薪资数据更新完成:', salaryData);
      } catch (error) {
        console.error('获取薪资数据失败:', error);
        // 设置默认空数据以避免页面空白
        companySalaryData.value = Array(selectedCompanyIndices.value.length).fill({levels: []});
      }
    };
// ... existing code ...
    // 根据薪资计算高度
    const calculateHeight = (minSalary, maxSalary) => {
      const avgSalary = (minSalary + maxSalary) / 2;
      // 根据薪资水平计算高度，参考原来的数值范围
      const minHeight = 80;
      const maxHeight = 240;
      const minSalaryRef = 200000;
      const maxSalaryRef = 3000000;
      
      // 将薪资映射到高度范围
      const height = minHeight + (avgSalary - minSalaryRef) / (maxSalaryRef - minSalaryRef) * (maxHeight - minHeight);
      return Math.min(maxHeight, Math.max(minHeight, height));
    };

    const toggleCompany = (index) => {
      const idx = selectedCompanyIndices.value.indexOf(index);
      if (idx === -1) {
        if (selectedCompanyIndices.value.length >= 6) {
          alert("最多只能选择 5 家公司");
          return;
        }
        selectedCompanyIndices.value.push(index);
        // 重新获取薪资数据
        fetchSalaryData();
      } else {
        selectedCompanyIndices.value.splice(idx, 1);
        // 重新获取薪资数据
        fetchSalaryData();
      }
    };

    // 获取公司在原始数组中的索引
    const getCompanyOriginalIndex = (company) => {
      return companies.value.findIndex(c => c.id === company.id);
    };   
    
    // 新增：处理搜索变化的方法
    const handleSearchChange = (value) => {
      if (!value) return;

      const companyIndex = companies.value.findIndex(company => company.id === value);
      if (companyIndex === -1) return;

      const selectedIndex = selectedCompanyIndices.value.indexOf(companyIndex);

      if (selectedIndex !== -1) {
        selectedCompanyIndices.value.splice(selectedIndex, 1);
      } else {
        if (selectedCompanyIndices.value.length >= 5) {
          selectedCompanyIndices.value.pop();
        }
        selectedCompanyIndices.value.push(companyIndex);
      }
      
      // 重新获取薪资数据
      fetchSalaryData();

      searchQuery.value = '';
    };
        
    // 新增：添加薪酬的方法
    const addSalary = () => {
      
      // 这里可以添加逻辑来打开添加薪酬的弹窗或表单
      router.push('/addsalary')
    };

    const getCompanyName = (index) => {
      const company = companies.value[index];
      return company ? company.name : '';
    };

    const getCompanyLogo = (index) => {
      const company = companies.value[index];
      return company ? (company.logo || company.name.charAt(0).toUpperCase()) : '';
    };

    // 获取公司的logo_url
    const getCompanyLogoUrl = (index) => {
      const company = companies.value[index];
      return company ? company.logo_url : '';
    };

    // 获取完整的logo URL（包括基础URL）
    const getFullLogoUrl = (logoUrl) => {
      if (!logoUrl) return '';
      
      // 如果logo_url已经是完整URL，则直接返回
      if (logoUrl.startsWith('http')) {
        return logoUrl;
      }
      
      // 否则加上基础URL
      const baseUrl = apiConfig.imageBaseURL.development;
      // 处理路径中的重复斜杠
      if (logoUrl.startsWith('/')) {
        return baseUrl + logoUrl;
      } else {
        return baseUrl + '/' + logoUrl;
      }
    };

    // 修复：将openSalaryDialog函数定义移到setup函数内部
    const openSalaryDialog = (colIndex) => {
      if (companySalaryData.value[colIndex]) {
        currentSalaryData.value = companySalaryData.value[colIndex];
        dialogVisible.value = true;
      }
    };

    const processedColumns = computed(() => {
      const cols = [];
      selectedCompanyIndices.value.forEach((idx, colIndex) => {
        const data = companySalaryData.value[colIndex];
        if (!data || !data.levels) return;

        const col = data.levels.map((level, index) => {
          const minSalary = level.min_salary ? (level.min_salary / 10000).toFixed(0) : 0;
          const maxSalary = level.max_salary ? (level.max_salary / 10000).toFixed(0) : 0;
          const salaryRange = `¥${minSalary}-${maxSalary}万`;

          // 使用计算的高度值
          const height = level.height || 100;

          // 根据高度动态调整字体大小，确保文字不溢出
          const baseFontSize = 10;
          const minHeightForText = 90; // 最小高度，低于此高度时字体最小
          const maxHeightForText = 240; // 最大高度，高于此高度时字体最大
          
          // 计算字体大小：高度越低，字体越小
          let fontSize = baseFontSize;
          if (height < minHeightForText) {
            fontSize = Math.max(8, baseFontSize * (height / minHeightForText));
          } else if (height > maxHeightForText) {
            fontSize = Math.min(20, baseFontSize * (height / maxHeightForText));
          } else {
            fontSize = baseFontSize * (height / maxHeightForText);
          }

          return {
            level: level.level_code || '',
            title: level.level_name || '',
            salary: salaryRange,
            height,
            fontSize: Math.round(fontSize)
          };
        });
        cols.push(col);
      });

      return cols;
    });
    
    // 添加移动列的方法
    const moveColumnLeft = (colIndex) => {
      if (colIndex > 0) {
        const newIndices = [...selectedCompanyIndices.value];
        [newIndices[colIndex], newIndices[colIndex - 1]] = [newIndices[colIndex - 1], newIndices[colIndex]];
        selectedCompanyIndices.value = newIndices;
        // 重新获取薪资数据
        fetchSalaryData();
      }
    };
    
    const moveColumnRight = (colIndex) => {
      if (colIndex < selectedCompanyIndices.value.length - 1) {
        const newIndices = [...selectedCompanyIndices.value];
        [newIndices[colIndex], newIndices[colIndex + 1]] = [newIndices[colIndex + 1], newIndices[colIndex]];
        selectedCompanyIndices.value = newIndices;
        // 重新获取薪资数据
        fetchSalaryData();
      }
    };
    
    // 组件挂载时获取公司数据
    onMounted(async () => {
      await fetchCompanies();
      await fetchSalaryData(); // 确保在获取公司数据后获取薪资数据
      console.log('已加载公司数据');
    });

    return {
      dialogVisible,
      currentSalaryData,
      companySalaryData,
      openSalaryDialog,
      toggleCompany,
      processedColumns,
      visibleCompanies,
      selectedCompanyIndices,
      searchQuery,
      handleSearchChange,
      addSalary,
      companies,
      getCompanyOriginalIndex,
      getCompanyName,
      getCompanyLogo,
      getCompanyLogoUrl,
      getFullLogoUrl,
      moveColumnLeft,
      moveColumnRight
    };
  },

  methods: {
    getColumnGradient(colIndex) {
      const gradients = [
       "rgba(255, 105, 180, 0.4), rgba(255, 105, 180, 1)",   // PayPay - 粉红
        "rgba(144, 238, 144, 0.4), rgba(144, 238, 144, 1)",   // 谷歌 - 浅绿
        "rgba(173, 173, 214, 0.4), rgba(173, 173, 214, 1)" ,   // 脸书 - 浅蓝
         "rgba(52, 152, 219, 0.4), rgba(52, 152, 219, 1)",   // 腾讯 - 蓝色（统一风格）
        "rgba(231, 76, 60, 0.4), rgba(243, 156, 18, 1)",   // 华为 
        "rgba(39, 174, 96, 0.4), rgba(162, 228, 184, 1)",   // 百度 
        "rgba(241, 196, 15, 0.4), rgba(243, 156, 18, 1)",   // 京东 
        "rgba(155, 89, 182, 0.4), rgba(142, 68, 173, 1)",   // 小米 
        "rgba(46, 204, 113, 0.4), rgba(241, 196, 15, 1)",   // 网易 
        "rgba(211, 84, 0, 0.4), rgba(243, 156, 18, 1)"    // 滴滴 
      ];
      return gradients[colIndex % gradients.length];
    },
   
 
  },

  mounted() {
    // 初始化时加载假数据
    console.log('组件已挂载');
  }
};
</script>


<style scoped>
.salary-comparison {
  padding: 20px;
  font-family: "Microsoft YaHei", sans-serif;
}

.company-header {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 20px;
  flex-wrap: wrap;
}
.company-header-title{
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  margin-bottom: 5px;
}
.company-header-in-chart {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  padding: 5px 6px;
  font-weight: bold;
  font-size: 12px;
  color: white;
  background-color: #007aff;
  border-bottom: 1px solid rgba(255, 255, 255, 0.3);
  position: relative;
  width: 50%;
  border-radius: 20px;
  /* margin-bottom: 5px; */
}
.arrow{
  font-size: 18px;
}

.company-tab {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 8px 16px;
  border-radius: 20px;
  background-color: #fff;
  border: 1px solid #ccc;
  cursor: pointer;
  transition: all 0.2s ease;
  box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}

.company-tab:hover {
  border-color: #007aff;
  box-shadow: 0 2px 6px rgba(0,0,0,0.15);
}

.company-tab.active {
  color: #007aff;
  background-color: white;
  border-color: #007aff;
}

.company-logo-image {
  width: 20px;
  height: 20px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
}

.company-logo-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.company-logo {
  font-weight: bold;
  /* font-size: 14px; */
}

/* .company-name {
  font-size: 14px;
} */

.company-count {
  font-size: 12px;
  
}

.company-count.active{
  color: #007aff!important;
}

/* 搜索容器 */
.search-container {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-left: auto;
  color: #000;
}

/* 瀑布流图表 */
.career-chart {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  cursor: pointer;
  transition: transform 0.2s;
  margin: 0 1px;
  display: flex;
  flex-direction: column;
  min-height: 100px;
  width: 100%;
}

.career-chart:hover {
  transform: scale(1.02);
  z-index: 2;
  box-shadow: 0 6px 18px rgba(0, 0, 0, 0.15);
}


.row {
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
  background-color: rgba(255, 255, 255, 0.3);
  border-bottom: 1px solid rgba(255, 255, 255, 0.5);
  transition: all 0.2s;
  overflow: hidden;
  flex-shrink: 0;
}

.content-wrapper {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  text-align: center;
  width: 100%;
  padding: 5px;
  box-sizing: border-box;
}

.level {
  font-weight: bold;
  letter-spacing: 1px;
  font-size: 16px;
}

.title {
  margin-bottom: 5px;
  font-size: 14px;
}

.salary {
  font-weight: bold;
  color: #5c3d00;
  letter-spacing: 1px;
  font-size: 14px;
}
/* 响应式 */
@media (max-width: 840px) {
  .career-chart {
    width: 95%;
  }
  
  .row {
    height: auto !important;
    padding: 10px 5px !important;
  }
}
</style>